﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WindowsInput;
using System.Net;
using System.IO;
using System.Web;
using System.Text.RegularExpressions;
using Twitterizer;

namespace AutoTweet
{
    public partial class Form1 : Form
    {
        private string consumerKey = "5x3bnW9mwhziiGx1ZkWLg";
        private string consumerSecretKey = "mQ6eo4bwmTfqvyC1qz2Me8avRpEMj7LXB61jHYWC0k8";

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            

        }

        private void button2_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("http://twitter.com");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //webBrowser2.Navigate("http://twitter.com");
            Form2 f2 = new Form2();
            f2.Show();
        }

        private string ue(string parm, string val)
        {
            return HttpUtility.UrlEncode(parm) + "=" + HttpUtility.UrlEncode(val);
        }

        int countUsername = 0;
        bool hasFillPassword = false;
        private void button4_Click(object sender, EventArgs e)
        {
            var root = webBrowser1.Document.GetElementById("signin-dropdown");
            var textboxes = root.GetElementsByTagName("input");
            foreach (HtmlElement textbox in textboxes)
            {
                if (textbox.Name.ToLower() == "session[username_or_email]")
                {
                    //if (!hasFillPassword)
                    //{

                    //if (countUsername == 1)
                    //{
                     //textbox.InvokeMember("focus");
                     //InputSimulator.SimulateTextEntry("bamby084");
                    // }
                    //countUsername++;
                    //hasFillPassword = true;
                    // }
                    //textbox.InnerText = "bamby084";
                }
                else if (textbox.Name.ToLower() == "session[password]")
                    textbox.InnerText = "201084";
            }

            var buttons = root.GetElementsByTagName("button");
            buttons[0].InvokeMember("click");
        }

        private void button5_Click(object sender, EventArgs e)
        {
            var tweetbox = webBrowser1.Document.GetElementById("main-tweet-box");
            var textareas = tweetbox.GetElementsByTagName("textarea");

            textareas[0].InnerText = "hello from C#";

            var links = tweetbox.GetElementsByTagName("a");
            links[1].InvokeMember("click");
        }

        private void button6_Click(object sender, EventArgs e)
        {
            string postData =  "session[username_or_email]=" + "bamby084" + "&session[password]=" + "201084" + "&return_to_ssl=true&redirect_after_login=";
            CookieContainer cc = new CookieContainer();
            string homepage = getContent("http://twitter.com", "", "", null, ref cc);
            CookieContainer newcc = new CookieContainer();
            string newret = getContent("https://twitter.com/sessions?phx=1", postData, "https://twitter.com/#!/login/", cc, ref newcc);
            return;
            //textBox1.Focus();
            //InputSimulator.SimulateTextEntry("hello");
            //var proxyList = AutoTweet.Ultilities.Common.GetInternetProxyListFromFile(@"d:\ip_proxy2.txt");
            //bool b = AutoTweet.Utilities.Twitter.VerifyAccount("bamby084", "201084");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://api.twitter.com/1/statuses/update.json");
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:7.0) Gecko/20100101 Firefox/7.0";
            CookieContainer c = new CookieContainer();
            var n = (new Uri("http://twitter.com"));
            request.CookieContainer = c;
            byte[] data = Encoding.UTF8.GetBytes("include_entities=true&status=hellfromcs&post_authenticity_token=640f5a0f5476ea68214152463192c59b16b3609e");
            request.ContentLength = data.Length;

            Stream dataStream = request.GetRequestStream();
            dataStream.Write(data, 0, data.Length);
            dataStream.Close();



            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            MessageBox.Show(response.StatusCode.ToString());
        }

        public void authenticate()
        {
            DateTime tmp = DateTime.Now;

            var oAuth = new oAuthTwitter();
            oAuth.ConsumerKey = consumerKey;
            oAuth.ConsumerSecret = consumerSecretKey;

            Uri AuthUri = new Uri(oAuth.AuthorizationLinkGet());
            var _token = HttpUtility.ParseQueryString(AuthUri.Query)["oauth_token"];
            CookieContainer cookies = null;
            string content = getContent(AuthUri.ToString(), null, "", null, ref cookies);
            string authenticity_token = Regex.Match(content, "twttr\\.form_authenticity_token = '([^']+)';", RegexOptions.IgnoreCase).Groups[1].Value;

            string post = ue("authenticity_token", authenticity_token) +
                            "&" + ue("oauth_token", _token) +
                            "&" + ue("session[username_or_email]", "bamby0843") +
                            "&" + ue("session[password]", "201084") + "&Allow=allow";

            content = getContent(oAuthTwitter.AUTHORIZE, post, "https://www.twitter.com/", cookies, ref cookies);
            Match m = Regex.Match(content, "oauth_pin\\\">\\s*([0-9]+)", RegexOptions.IgnoreCase);
            var _pin = "";
            if (m != null)
            {
                _pin = m.Groups[1].Value;
            }

            oAuth.Token = _token;
            oAuth.AccessTokenGet(_token, _pin);
            /*if (oAuth.TokenSecret.Length > 0)
            {
                string xml = oAuth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://twitter.com/account/verify_credentials.xml", String.Empty);
            }*/
            OAuthTokens token = new OAuthTokens();
            token.ConsumerKey = consumerKey;
            token.ConsumerSecret = consumerSecretKey;
            token.AccessToken = oAuth.Token;
            token.AccessTokenSecret = oAuth.TokenSecret;

            var response = TwitterStatus.Update(token, DateTime.Now.ToString());
            TimeSpan span = DateTime.Now.TimeOfDay - tmp.TimeOfDay;
            MessageBox.Show(response.Result.ToString() + ":" + span.TotalSeconds.ToString());
        }

        private void Login()
        {
            ServicePointManager.Expect100Continue = false;
            string postData = "session[username_or_email]=" + "bamby084" + "&session[password]=" + "201084" + "&return_to_ssl=true&redirect_after_login=http://www.google.com";
            //string postData = String.Format("username={0}&passwd={1}", "bamby084", "test039rink613");
            CookieContainer tempCookies = new CookieContainer();
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] byteData = encoding.GetBytes(postData);

            HttpWebRequest postReq = (HttpWebRequest)WebRequest.Create("https://twitter.com/sessions?phx=1");
            //HttpWebRequest postReq = (HttpWebRequest)WebRequest.Create("https://login.yahoo.com/config/login_verify2?&.src=ym");
            postReq.Method = "POST";
            postReq.KeepAlive = true;
            postReq.CookieContainer = tempCookies;
            postReq.ContentType = "application/x-www-form-urlencoded";
            postReq.Referer = "https://twitter.com/#!/login/";
            postReq.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)";
            postReq.ContentLength = byteData.Length;

            //Stream postreqstream = postReq.GetRequestStream();
            //postreqstream.Write(byteData, 0, byteData.Length);
            //postreqstream.Close();
            StreamWriter sw = new StreamWriter(postReq.GetRequestStream());
            sw.Write(postData);
            sw.Flush();
            sw.Close();


            HttpWebResponse postresponse = (HttpWebResponse)postReq.GetResponse();
            StreamReader reader = new StreamReader(postresponse.GetResponseStream());
            string tmp = reader.ReadToEnd();
            MessageBox.Show(postresponse.StatusCode.ToString());

        }

        private string getContent(string url, string requestBody, string referrer, CookieContainer cookies, ref CookieContainer retCookies)
        {
            ServicePointManager.Expect100Continue = false;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = string.IsNullOrEmpty(requestBody) ? "GET" : "POST";
            request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729)";
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            request.KeepAlive = true;
            request.Referer = referrer;
            request.CookieContainer = cookies;

            if (!string.IsNullOrEmpty(requestBody))
            {
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = Encoding.UTF8.GetByteCount(requestBody);
                Stream requestStream = request.GetRequestStream();
                StreamWriter sw = new StreamWriter(requestStream);
                sw.Write(requestBody);
                sw.Flush();
                sw.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader sr = new StreamReader(stream);
            string content = sr.ReadToEnd();

            CookieContainer rc = new CookieContainer();
            rc.SetCookies(new Uri("http://twitter.com"), response.Headers["Set-Cookie"]);
            rc.Add(response.Cookies);

            retCookies = rc;

            return content;
        }

        private void button7_Click(object sender, EventArgs e)
        {
            /*AutoTweet.Utilities.WebBrowserWithProxy wb = new AutoTweet.Utilities.WebBrowserWithProxy();
            wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
            ticks = DateTime.Now;
            wb.Navigate("http://twitter.com");*/
            authenticate();
        }

        private bool hasLogin = false;
        private DateTime ticks;
        private bool hasFinish = false;
        void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (hasFinish)
                return;

            var wb = sender as AutoTweet.Utilities.WebBrowserWithProxy;
            if (!hasLogin)
            {
                DoLogin(wb.Document, "bamby084", "201084");
                hasLogin = true;
            }
            else
            {
                Tweet(wb.Document, "hello from C#");
                TimeSpan span = DateTime.Now - ticks;
                MessageBox.Show(span.TotalSeconds.ToString());
                hasFinish = true;
            }
        }

        private void DoLogin(HtmlDocument document, string username,string password)
        {
            var divParent = document.GetElementById("signin-dropdown");
            var inputs = divParent.GetElementsByTagName("input");
            
            foreach (HtmlElement input in inputs)
            {
                if (input.Name.ToLower() == "session[username_or_email]")
                    input.InnerText = username;
                else if (input.Name.ToLower() == "session[password]")
                    input.InnerText = password;
            }

            var buttons = divParent.GetElementsByTagName("button");
            buttons[0].InvokeMember("click");
        }

        private void Tweet(HtmlDocument document, string message)
        {
            var tweetbox = document.GetElementById("main-tweet-box");
            var textareas = tweetbox.GetElementsByTagName("textarea");

            textareas[0].InnerText = message;

            var links = tweetbox.GetElementsByTagName("a");
            links[1].InvokeMember("click");
        }

        private void button8_Click(object sender, EventArgs e)
        {
            DateTime tmp = DateTime.Now;
            OAuthTokens token = new OAuthTokens();
            token.ConsumerKey = consumerKey;
            token.ConsumerSecret = consumerSecretKey;
            token.AccessToken = "381288804-91X3pi8M27K2CxIwSiJyXrIrDXqaw1QUt19cnKpJ";
            token.AccessTokenSecret = "K78QPOqhlDEc5vOhJs5B0m3chrwGPWdMbJRkQJeMY";

            var response = TwitterStatus.Update(token, DateTime.Now.ToString());
            TimeSpan span = DateTime.Now.TimeOfDay - tmp.TimeOfDay;
            MessageBox.Show(response.Result.ToString() + ":" + span.TotalSeconds.ToString());
        }
    }
}
